


/**
 * ajax请求封装
 * token与userinfo逻辑的封装
 * 
 * @param {*} params // {method,url,data,headers}
 * @param {*} cb 
 */
const ajax = (params, cb) => {

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function (event) {
        if (cb) {
            var dataJson = JSON.parse(event.target.responseText);
            cb(dataJson);
        }
    }

    xmlhttp.onerror = xmlhttp.onabort = function (event) {
        console.log(event.target.responseText);
    }

    // 默认为get方法
    params.method = params.method || 'get';
    params.method = params.method.toLowerCase();
    params.async = params.async || true;

    var requestOrigin = window.requestOrigin;
    var url = params.fullUrl ? params.fullUrl : requestOrigin + params.url;
    if (url) {
        xmlhttp.open(params.method, url, params.async);
        if (params.method === "post") {
            xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        }
        // 头部设置
        if (params.headers) {
            for (var i = 0; i < params.headers.length; i++) {
                for (var j in params.headers[i]) {
                    xmlhttp.setRequestHeader(j, params.headers[i][j]);
                }

            }
        }
    } else {
        return console.error('No Url !')
    }

    if (params.data) {
        xmlhttp.send(JSON.stringify(params.data));
    } else {
        xmlhttp.send();
    }
    return xmlhttp;
}

export default ajax;

